<template>
  <div class="box">
    <div class="container-box">
      <i class="topL"></i>
      <i class="topR"></i>
      <i class="bottomL"></i>
      <i class="bottomR"></i>
      <div id="container">
      </div>
    </div>
    <!--无人机列表-->
    <div class="uav-list">
      <div class="data-box box-back">
        <i class="topL"></i>
        <i class="topR"></i>
        <i class="bottomL"></i>
        <i class="bottomR"></i>
        <div class="data-title">
          <b class="data-title-left">[</b>
          <div>无人机列表</div>
          <b class="data-title-right">]</b>
        </div>

      </div>
    </div>
    <!--查询标注-->
    <div class="check-box">
      <div class="data-box box-back">
        <i class="topL"></i>
        <i class="topR"></i>
        <i class="bottomL"></i>
        <i class="bottomR"></i>
        <!--标题-->
        <div class="data-title">
          <b class="data-title-left">[</b>
          <div>查询标注</div>
          <b class="data-title-right">]</b>
        </div>
        <!--功能路由-->
        <div class="func-route">
          <div class="route-heard">
            <div
                class="func-item"
                v-for="(item,index) in routeList"
                :key="index"
                :class="checktIndex === index ? 'active' : ''"
                @click="isActive(index)"
            >
              {{ item.name }}
            </div>
          </div>
          <div class="func">
            <div class="label" v-if="labelShow">
              <div class="choose-label">
                <el-select
                    v-model="labelValue"
                    placeholder="选择类型"
                    style="width: 6vw"
                    @change="labelChange"
                >
                  <el-option
                      v-for="item in LabelOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                  />
                </el-select>
                <el-button @click="startDraw" style="margin-left: 1vw;">
                  添加标注
                </el-button>
              </div>
              <div class="label-list">
                <div class="list" v-if="labelList.length">
                  <el-table
                      :data="labelList"
                      border
                      style="width: 100%;height: 37vh;"
                      max-height="37vh"
                      empty-text="暂无此类型标注"
                  >
                    <el-table-column
                        type="index"
                        width="30"
                        align="center"
                    />
                    <el-table-column
                        prop="name"
                        label="名称"
                        width="100"
                        align="center"
                    />
                    <el-table-column
                        prop="description"
                        label="描述"
                        width="100"
                        align="center"
                    />
                    <el-table-column
                        label="操作"
                        align="center"
                    >
                      <template #default="{row}">
                        <el-button size="small" @click="showEditForm(row.id)">
                          编辑
                        </el-button>
                        <el-button size="small" @click="flyToField(row)">
                          定位
                        </el-button>
                        <el-button size="small" @click="delField(row.id)">
                          删除
                        </el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
                <div class="empty" v-else>
                  暂无标注
                </div>
              </div>
            </div>
            <div class="search" v-else>
              <div class="search-btn">
                <el-button
                    @click="showSearchDia"
                    size="small"
                >
                  查询
                </el-button>
              </div>
              <div class="search-list">
                <div class="list" v-if="searchList.length">
                  <el-table
                      :data="searchList"
                      border
                      style="width: 100%;height: 37vh;"
                      max-height="37vh"
                      empty-text="未查询到数据"
                  >
                    <el-table-column
                        type="index"
                        width="30"
                        align="center"
                    />
                    <el-table-column
                        prop="name"
                        label="名称"
                        width="100"
                        align="center"
                    />
                    <el-table-column
                        prop="description"
                        label="描述"
                        width="100"
                        align="center"
                    />
                    <el-table-column
                        label="操作"
                        align="center"
                    >
                      <template #default="{row}">
                        <el-button size="small" @click="showEditForm(row.id)">
                          编辑
                        </el-button>
                        <el-button size="small" @click="flyToField(row)">
                          定位
                        </el-button>
                        <el-button size="small" @click="delField(row.id)">
                          删除
                        </el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
                <div class="empty">
                  点击查询按钮开始查询
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!--无人机画面-->
    <div class="uav-live">
      <div class="data-box box-back">
        <i class="topL"></i>
        <i class="topR"></i>
        <i class="bottomL"></i>
        <i class="bottomR"></i>
        <!--标题-->
        <div class="data-title">
          <b class="data-title-left">[</b>
          <div>实时画面</div>
          <b class="data-title-right">]</b>
        </div>
      </div>
    </div>
    <!--无人机画面-->
    <div class="uav-live-info">
      <div class="data-box box-back">
        <i class="topL"></i>
        <i class="topR"></i>
        <i class="bottomL"></i>
        <i class="bottomR"></i>
        <!--标题-->
        <div class="data-title">
          <b class="data-title-left">[</b>
          <div>实时信息</div>
          <b class="data-title-right">]</b>
        </div>
      </div>
    </div>
    <!--分析统计-->
    <div class="uav-charts">
      <div class="data-box box-back">
        <i class="topL"></i>
        <i class="topR"></i>
        <i class="bottomL"></i>
        <i class="bottomR"></i>
        <!--标题-->
        <div class="data-title">
          <b class="data-title-left">[</b>
          <div>数据统计</div>
          <b class="data-title-right">]</b>
        </div>
        <div class="func-route">
          <div class="route-heard">
            <div
                class="func-item"
                v-for="(item,index) in chartList"
                :key="index"
                :class="chartIndex === index ? 'active' : ''"
                @click="isChartActive(index)"
            >
              {{ item.name }}
            </div>
          </div>
        </div>
        <div class="distance" id="distance" v-if="chartIndex === 0"></div>
        <div class="task" id="task" v-else-if="chartIndex === 1"></div>
        <div class="person" id="person" v-else-if="chartIndex === 2"></div>
      </div>
    </div>
  </div>

  <div class="add-box" v-if="isAddShow">
    <div class="add-title">
      <div>
        添加标注
      </div>
      <div
          class="right"
          style="color: black;line-height: 2vh;vertical-align: middle;"
      >
        <el-icon
            style="vertical-align: middle"
            @click="cancelAdd"
        >
          <Close />
        </el-icon>
      </div>
    </div>
    <div class="add-body">
      <el-form :model="addForm" label-width="auto">
        <el-form-item label="名称">
          <el-input v-model="addForm.name" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="addForm.description" />
        </el-form-item>
        <el-form-item label="上传人">
          <el-input v-model="addForm.person" />
        </el-form-item>
        <el-form-item label="将数据存储为">
          <el-select v-model="addForm.type" placeholder="选择类型" @change="selectChanged">
            <el-option
                v-for="item in addTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <div class="btn">
            <el-button @click="reDraw">重新取点</el-button>
            <el-button @click="cancelAdd">取消</el-button>
            <el-button type="primary" @click="onAdd">添加</el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>

  <div class="edit-box" v-if="isEditShow">
    <div class="edit-title">
      <div>
        编辑标注
      </div>
      <div
          class="right"
          style="color: black;line-height: 2vh;vertical-align: middle;"
      >
        <el-icon
            style="vertical-align: middle"
            @click="cancelEdit"
        >
          <Close />
        </el-icon>
      </div>
    </div>
    <div class="edit-body">
      <el-form :model="editForm" label-width="auto">
        <el-form-item label="修改属性">
          <el-select v-model="editForm.field" placeholder="选择类型" @change="selectChanged">
            <el-option
                v-for="item in fieldOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="新属性值">
          <el-input v-model="editForm.value" />
        </el-form-item>
        <el-form-item>
          <div class="btn">
            <el-button type="primary" @click="onEditField">确认</el-button>
            <el-button @click="cancelEdit">取消</el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>

  <el-dialog
      v-model="searchDialogVisible"
      title="填写查询条件"
      width="500"
      :before-close="handleSearchClose"
      style="font-family: dingding"
      :close-on-click-modal="false"
  >
    <el-form :model="searchForm" label-width="auto" style="max-width: 600px">
      <el-form-item label="选择标注类型">
        <el-select
            v-model="searchForm.type"
            clearable
        >
          <el-option
              v-for="item in LabelOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="选择属性名">
        <el-select
            v-model="searchForm.field"
            clearable
        >
          <el-option
              v-for="item in fieldOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="属性值">
        <el-input v-model="searchForm.value" />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleSearchClose">取消</el-button>
        <el-button type="primary" @click="onSearch">
          查询
        </el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup>
import {nextTick, onMounted, reactive, ref} from "vue"
import {Close} from "@element-plus/icons-vue"
import * as echarts from 'echarts';
import {useRouter} from "vue-router"
import {createMsg, createMSG, generateRandomThreeDecimalPlaces} from "@/utils/common/common"
import {
  addLineField,
  addPointLabel,
  addPolygonField,
  delLine,
  delPolygon,
  delPositionLabel,
  editLineField,
  editPointLabel,
  editPolygonField,
  getLineByField,
  getLineList, getPointByField,
  getPointLabelList,
  getPolygonByField,
  getPolygonList
} from "@/api/Cesium"
import {ElDialog, ElButton, ElForm, ElFormItem, ElInput, ElTable, ElTableColumn} from "element-plus"

//#region
Cesium.Ion.defaultAccessToken ="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJmZmU4ODg5MS1mYTYxLTQ1MTMtOTM1My03YzhhMTM3ZWUxNDAiLCJpZCI6MTIyNTgyLCJpYXQiOjE2NzQ5NjQ0ODR9.e9Q99Z21wt6NjtUEtGHIjYoNq8WGHsisnoysbVptffE"
let TDU_Key = "0cc22d450bf67b7abb13e0e90ea233ae"; // 天地图申请的密钥
//#endregion
const router = useRouter()

const checktIndex = ref(0)
const chartIndex = ref(0)

const labelShow = ref(false)
const isAddShow = ref(false)
const searchDialogVisible = ref(false)

const routeList = [
  {
    name:'查询',
  },
  {
    name:'标注',
  },
]

const chartList = [
  {
    name:'里程'
  },
  {
    name:'任务'
  },
  {
    name:'人员'
  },
]

const addTypeOptions = [
  {
    label:'点标注',
    value:"point",
  },{
    label:'线标注',
    value:"polyline",
  },{
    label:'面标注',
    value:"polygon",
  },
]

const labelValue = ref(0)
const labelList = ref([])
const LabelOptions = [
  {
    label:'点标注',
    value:0,
  },{
    label:'线标注',
    value:1,
  },{
    label:'面标注',
    value:2,
  },
]

const addForm = reactive({
  geom:'',
  name:'',
  description:'',
  person:'',
  type:''
})

const targetTypeValue = ref('')

const isEditShow = ref(false)
const fieldOptions = [
  {
    label:'添加人',
    value:'person',
  },{
    label:'描述',
    value:'description',
  },{
    label:'名称',
    value:'name',
  },
]
let editForm = reactive({
  field:'',
  value:"",
  type:null
})
let currentEditLine = null

let searchForm = reactive({
  field:'',
  value:'',
  type:''
})
const searchList = ref([])

onMounted(()=>{
  initCesium();
  initCharts();
})

let viewer
const initCesium = async () => {
  viewer = new Cesium.Viewer("container", {
    animation: false,//动画小部件
    baseLayerPicker: false,//地图图层组件
    fullscreenButton: false,//全屏组件
    geocoder: false,//地理编码搜索组件
    homeButton: false,//首页组件
    // infoBox:true,//信息框
    infoBox:false,//信息框
    // sceneModePicker: false,//场景模式
    selectionIndicator: false,//选取指示器组件
    timeline: false,//时间轴
    navigationHelpButton: false,//帮助按钮
    navigationInstructionsInitiallyVisible: false,
    terrainProvider:await Cesium.createWorldTerrainAsync({
      // requestWaterMask: true,
    }), // 地形数据
  })
  viewer._cesiumWidget._creditContainer.style.display = "none";
  window.viewer = viewer
  viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK)
}

const isActive = (index) => {
  checktIndex.value = index
  if (index === 0){
    labelShow.value = false
    if (hightEntities.length){
      hightEntities.forEach(item=>{
        let t = window.viewer.entities.getById(item)
        if (t){
          window.viewer.entities.removeById(item)
        }
      })
      hightEntities = []
    }
  } else {
    labelShow.value = true
    labelChange()
  }
}

const isChartActive = (index) => {
  chartIndex.value = index
  setTimeout(()=>{
    initCharts()
  })
}

const initCharts = () => {
  let option,myChart,chartDom
  if (chartIndex.value === 0){
    chartDom = document.getElementById('distance')
    myChart = echarts.init(chartDom)
    option = {
      xAxis: {
        type: 'category',
        data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          data: [
            120,
            {
              value: 200,
              itemStyle: {
                color: '#a90000'
              }
            },
            150,
            80,
            70,
            110,
            130
          ],
          type: 'bar'
        }
      ]
    }
  }
  else if (chartIndex.value === 1){
    chartDom = document.getElementById('task')
    myChart = echarts.init(chartDom);
    let app = {}
    const posList = [
      'left',
      'right',
      'top',
      'bottom',
      'inside',
      'insideTop',
      'insideLeft',
      'insideRight',
      'insideBottom',
      'insideTopLeft',
      'insideTopRight',
      'insideBottomLeft',
      'insideBottomRight'
    ];
    app.configParameters = {
      rotate: {
        min: -90,
        max: 90
      },
      align: {
        options: {
          left: 'left',
          center: 'center',
          right: 'right'
        }
      },
      verticalAlign: {
        options: {
          top: 'top',
          middle: 'middle',
          bottom: 'bottom'
        }
      },
      position: {
        options: posList.reduce(function (map, pos) {
          map[pos] = pos;
          return map;
        }, {})
      },
      distance: {
        min: 0,
        max: 100
      }
    };
    app.config = {
      rotate: 90,
      align: 'left',
      verticalAlign: 'middle',
      position: 'insideBottom',
      distance: 15,
      onChange: function () {
        const labelOption = {
          rotate: app.config.rotate,
          align: app.config.align,
          verticalAlign: app.config.verticalAlign,
          position: app.config.position,
          distance: app.config.distance
        };
        myChart.setOption({
          series: [
            {
              label: labelOption
            },
            {
              label: labelOption
            },
            {
              label: labelOption
            },
            {
              label: labelOption
            }
          ]
        });
      }
    };
    const labelOption = {
      show: true,
      position: app.config.position,
      distance: app.config.distance,
      align: app.config.align,
      verticalAlign: app.config.verticalAlign,
      rotate: app.config.rotate,
      formatter: '{c}  {name|{a}}',
      fontSize: 16,
      rich: {
        name: {}
      }
    }
    option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      legend: {
        data: ['Forest', 'Steppe', 'Desert', 'Wetland']
      },
      toolbox: {
        show: true,
        orient: 'vertical',
        left: 'right',
        top: 'center',
        feature: {
          mark: { show: true },
          dataView: { show: true, readOnly: false },
          magicType: { show: true, type: ['line', 'bar', 'stack'] },
          restore: { show: true },
          saveAsImage: { show: true }
        }
      },
      xAxis: [
        {
          type: 'category',
          axisTick: { show: false },
          data: ['2012', '2013', '2014', '2015', '2016']
        }
      ],
      yAxis: [
        {
          type: 'value'
        }
      ],
      series: [
        {
          name: 'Forest',
          type: 'bar',
          barGap: 0,
          label: labelOption,
          emphasis: {
            focus: 'series'
          },
          data: [320, 332, 301, 334, 390]
        },
        {
          name: 'Steppe',
          type: 'bar',
          label: labelOption,
          emphasis: {
            focus: 'series'
          },
          data: [220, 182, 191, 234, 290]
        },
        {
          name: 'Desert',
          type: 'bar',
          label: labelOption,
          emphasis: {
            focus: 'series'
          },
          data: [150, 232, 201, 154, 190]
        },
        {
          name: 'Wetland',
          type: 'bar',
          label: labelOption,
          emphasis: {
            focus: 'series'
          },
          data: [98, 77, 101, 99, 40]
        }
      ]
    }
  }
  else if (chartIndex.value === 2){
    chartDom = document.getElementById('person')
    myChart = echarts.init(chartDom)
    option = {
      title: {
        text: 'Referer of a Website',
        subtext: 'Fake Data',
        left: 'center'
      },
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          name: 'Access From',
          type: 'pie',
          radius: '50%',
          data: [
            { value: 1048, name: 'Search Engine' },
            { value: 735, name: 'Direct' },
            { value: 580, name: 'Email' },
            { value: 484, name: 'Union Ads' },
            { value: 300, name: 'Video Ads' }
          ],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    }
  }
  option && myChart.setOption(option);
}


const labelChange = async () => {
  try {
    if (labelValue.value === 0){
      const {data:res} = await getPointLabelList()
      if (res.code === 200){
        labelList.value = res.data
      } else if (res.code === 201){
        labelList.value = []
        return createMSG('暂无点标注','success',true)
      }
    } else if (labelValue.value ===1){
      const {data:res} = await getLineList()
      if (res.code === 200){
        labelList.value = res.data
      } else if (res.code === 201){
        labelList.value = []
        return createMSG('暂无点标注','success',true)
      }
    } else if (labelValue.value === 2){
      const {data:res} = await getPolygonList()
      if (res.code === 200){
        labelList.value = res.data
      } else if (res.code === 201){
        labelList.value = []
        return createMSG('暂无点标注','success',true)
      }
    }
  } catch (e) {
    console.log(e)
  }
}

let handler,box
let addPositions = []
const startDraw = () => {
  addPositions = []
  const viewer = window.viewer
  createMsg('左键点击右上角地图取点开始画面，右键结束或取消','info',true)
  handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas)
  let drawing = []
  let polygon
  let cartesian
  handler.setInputAction(function (e){
    let ray = viewer.camera.getPickRay(e.position)
    cartesian = viewer.scene.globe.pick(ray,viewer.scene)
    let cartographic = Cesium.Cartographic.fromCartesian(cartesian)
    let lng = Cesium.Math.toDegrees(cartographic.longitude)
    let lat = Cesium.Math.toDegrees(cartographic.latitude)
    drawing.push(cartesian)
    addPositions.push([lng,lat])
    createPoint(lng,lat)
  },Cesium.ScreenSpaceEventType.LEFT_CLICK)

  handler.setInputAction(function (e){
    let ray = viewer.camera.getPickRay(e.endPosition)
    cartesian = viewer.scene.globe.pick(ray,viewer.scene)
    drawing.pop()
    drawing.push(cartesian)
    if (drawing.length >= 2){
      let cbPolygon = new Cesium.CallbackProperty(function (){
        return new Cesium.PolygonHierarchy(drawing)
      },false)
      polygon = createPolygon(cbPolygon,addPositions[0][0])
    }
  },Cesium.ScreenSpaceEventType.MOUSE_MOVE)

  handler.setInputAction(function (e){
    drawing.pop()
    createMsg('操作成功!','success')
    showAddForm()
    if (handler){
      handler.destroy()
      handler = null
    }
  },Cesium.ScreenSpaceEventType.RIGHT_CLICK)
}


const selectChanged = () => {
  if (addPositions.length > 1 && addForm.type === 'point'){
    addForm.type = ''
    createMsg('选择多点时不能存为点类标注','warning')
  } else if (addPositions.length < 3 && addForm.type === 'point'){
    addForm.type = ''
    createMsg('创建面类标注最少选择三个点','warning')
  }
}

const reDraw = () => {
  if (hightEntities.length){
    hightEntities.forEach(item=>{
      let t = window.viewer.entities.getById(item)
      if (t){
        window.viewer.entities.removeById(item)
      }
    })
    hightEntities = []
  }
  addPositions = []
  isAddShow.value = false
  addForm.type = ''
  addForm.name = ''
  startDraw()
}

const createPoint = (p1,p2) => {
  let num = generateRandomThreeDecimalPlaces()
  let e = window.viewer.entities.add({
    id:`point${num}`,
    position:Cesium.Cartesian3.fromDegrees(p1,p2),
    point:{
      pixelSize:5,
      color:Cesium.Color.CYAN,
      outlineColor:Cesium.Color.WHITE,
      outlineWidth:2,
      heightReference:Cesium.HeightReference.CLAMP_TO_GROUND
    }
  })
  hightEntities.push(`point${num}`)
  return e
}

const showAddForm = () => {
  if (addPositions.length === 1){
    addForm.type = 'point'
  } else if (addPositions.length === 2){
    addForm.type = 'polyline'
  }
  isAddShow.value = true
}

const createPolygon = (hierarchy) => {
  let num = generateRandomThreeDecimalPlaces()
  hightEntities.push(`polygon${num}`)
  return window.viewer.entities.add({
    id:`polygon${num}`,
    polygon:{
      hierarchy,
      material:new Cesium.ColorMaterialProperty(Cesium.Color.WHEAT.withAlpha(.4))
    }
  })
}

const onAdd = async() => {
  try {
    let res
    if (addPositions.length > 2 && addForm.type === 'point'){
      return createMsg('绘制多个点时只能保存为线类或面类标注','info')
    }
    if (addForm.type === 'polygon'){
      addPositions.push(addPositions[0])
      let str = ''
      for(let i = 0; i < addPositions.length; i++){
        if ( i === addPositions.length-1 ){
          str += `${addPositions[i][0]} ${addPositions[i][1]}`
        } else {
          str += `${addPositions[i][0]} ${addPositions[i][1]},`
        }
      }
      const response = await addPolygonField({
        geom: str,
        description:addForm.description,
        name:addForm.name,
        person:addForm.person,
      })
      res = response.data
    } else if (addForm.type === 'polyline'){
      let str = ''
      for(let i = 0; i < addPositions.length; i++){
        if ( i === addPositions.length-1 ){
          str += `${addPositions[i][0]} ${addPositions[i][1]}`
        } else {
          str += `${addPositions[i][0]} ${addPositions[i][1]},`
        }
      }
      const response = await addLineField({
        geom: str,
        description:addForm.description,
        name:addForm.name,
        person:addForm.person,
      })
      res = response.data
    } else if (addForm.type === 'point'){
      const response = await addPointLabel(`${addPositions[0][0]} ${addPositions[0][1]}`,addForm.description, addForm.name, addForm.person)
      res = response.data
    }
    if (res.code === 200){
      createMsg('创建成功!','success')
      isAddShow.value = false
      // box.style.visibility = 'visible'
      labelValue.value = addForm.type
      await labelChange()
      addForm.name = ''
      addForm.type = ''
      addForm.description = ''
      addForm.person = ''
      if (hightEntities.length){
        hightEntities.forEach(item=>{
          let t = window.viewer.entities.getById(item)
          if (t){
            window.viewer.entities.removeById(item)
          }
        })
        hightEntities = []
      }
    } else {
      createMsg('网络错误','info')
      isAddShow.value = false
      labelValue.value = addForm.type
      await labelChange()
      addForm.name = ''
      addForm.type = ''
      addForm.description = ''
      addForm.person = ''
      if (hightEntities.length){
        hightEntities.forEach(item=>{
          let t = window.viewer.entities.getById(item)
          if (t){
            window.viewer.entities.removeById(item)
          }
        })
        hightEntities = []
      }
    }
  } catch (e) {
    createMsg('创建失败','warning')
    console.log(e)
  }
}

const showEditForm = (id) => {
  currentEditLine = id
  isEditShow.value = true
}

const cancelEdit = () => {
  isEditShow.value = false
  editForm.value = ''
  editForm.field = ''
  editForm.type = null
  currentEditLine = null
}

const cancelAdd = () => {
  if (hightEntities.length){
    hightEntities.forEach(item=>{
      let t = window.viewer.entities.getById(item)
      if (t){
        window.viewer.entities.removeById(item)
      }
    })
    hightEntities = []
  }
  addPositions = []
  addForm.type = ''
  addForm.name = ''
  isAddShow.value = false
}

const onEditField = async () => {
  try {
    let res
    if (labelValue.value === 0){
      const data = await editPointLabel({
        field:editForm.field,
        value:editForm.value,
        id:currentEditLine
      })
      res = data.data
    } else if (labelValue.value === 1){
      const data = await editLineField({
        field: editForm.field,
        value: editForm.value,
        id: currentEditLine
      })
      res = data.data
    } else if (labelValue.value === 2){
      const data = await editPolygonField({
        field: editForm.field,
        value: editForm.value,
        id: currentEditLine
      })
      res = data.data
    }
    if (res.code === 200){
      isEditShow.value = false
      await labelChange()
      createMSG('操作成功!','success',true)
      // labelList.value = res.data
      editForm.field = ''
      editForm.value = ''
    } else {
      isEditShow.value = false
      editForm.field = ''
      editForm.value = ''
      currentEditLine = null
      await labelChange()
      return createMSG('网络错误','info',true)
    }
  } catch (e) {
    console.log(e)
  }
}


let hightEntities = []
const flyToField = (row) => {
  if (hightEntities.length){
    hightEntities.forEach(item=>{
      let t = window.viewer.entities.getById(item)
      if (t){
        window.viewer.entities.removeById(item)
      }
    })
    hightEntities = []
  }
  let coordinates = JSON.parse(row.geom).coordinates
  let entity
  if (labelValue.value === 0){
    entity = createPoint(coordinates[0],coordinates[1])
    window.viewer.flyTo(entity)
  } else if (labelValue.value === 1){
    let dataArr = []
    for(let i = 0; i < coordinates.length; i++){
      let cartesian = Cesium.Cartesian3.fromDegrees(coordinates[i][0],coordinates[i][1])
      dataArr.push(cartesian)
    }
    let num = generateRandomThreeDecimalPlaces()
    entity = window.viewer.entities.add({
      id:`label${num}`,
      polyline:{
        positions:dataArr,
        material:new Cesium.PolylineOutlineMaterialProperty({
          color: Cesium.Color.ORANGE,
          outlineWidth: 1,
          outlineColor: Cesium.Color.BLACK,
        }),
        width:3,
        clampToGround:true
      }
    })
    hightEntities.push(`label${num}`)
    window.viewer.flyTo(entity)
  } else if (labelValue.value === 2){
    let dataArr = []
    for(let i = 0; i < coordinates[0].length; i++){
      dataArr.push(coordinates[0][i][0],coordinates[0][i][1])
    }
    // console.log(info.coordinates,dataArr,info)

    let num = generateRandomThreeDecimalPlaces()
    entity = window.viewer.entities.add({
      id:`polygon${num}`,
      polygon:{
        hierarchy:{
          positions:Cesium.Cartesian3.fromDegreesArray(dataArr),
        },
        material:Cesium.Color.BLUE.withAlpha(0.5),
        heightReference:Cesium.HeightReference.CLAMP_TO_GROUND
      }
    })
    hightEntities.push(`polygon${num}`)
    window.viewer.flyTo(entity)
  }
  setTimeout(()=>{
    if (hightEntities.length){
      hightEntities.forEach(item=>{
        let t = window.viewer.entities.getById(item)
        if (t){
          window.viewer.entities.removeById(item)
        }
      })
      hightEntities = []
    }
  },3000)
}

const delField = async (id) => {
  try {
    let res
    if (labelValue.value === 0){
      const data = await delPositionLabel(id)
      res = data.data
    } else if (labelValue.value === 1){
      const data = await delLine(id)
      res = data.data
    } else if (labelValue.value === 2){
      const data = await delPolygon(id)
      res = data.data
    }
    if (res.code === 200){
      await labelChange()
      return createMSG('操作成功!','success',true)
    } else {
      await labelChange()
      return createMSG('操作失败!','info',true)
    }
  } catch (e) {
    console.log(e)
  }
}

const showSearchDia = () => {
  searchDialogVisible.value = true
}

const handleSearchClose = () => {
  searchDialogVisible.value = false
  searchForm.value = ''
  searchForm.field = ''
  searchForm.type = ''
}

const onSearch = async () => {
  try {
    let res
    if (searchForm.type === 0){
      const data = await getPointByField({
        field:searchForm.field,
        value:searchForm.value,
      })
      res = data.data
    } else if (searchForm.type === 1){
      const data = await getLineByField({
        field:searchForm.field,
        value:searchForm.value,
      })
      res = data.data
    } else if (searchForm.type === 2){
      const data = await getPolygonByField({
        field:searchForm.field,
        value:searchForm.value,
      })
      res = data.data
    }
    console.log(res)
    if (res.code === 200){
      handleSearchClose()
      searchList.value = res.data
    } else if (res.code === 201) {
      handleSearchClose()
      searchList.value = []
      createMSG('未查询到满足条件的数据','info',true)
    } else if (res.code === 400) {
      handleSearchClose()
      searchList.value = []
      createMSG('网络错误','info',true)
    }
  } catch (e) {
    console.log(e)
  }
}
</script>

<style scoped lang="less">
.box{
  height: 100%;
  width: 100%;
  background-color: rgba(243, 241, 236);
  overflow: hidden;
  .container-box{
    position: absolute;
    top: 9%;
    left: 69.5%;
    z-index: 1000;
    height: 31.4%;
    width: 30%;
    #container{
      overflow: hidden;
    }
  }
  .uav-list{
    position: absolute;
    top: 9%;
    left: 1%;
    width: 23%;
    height: 100%;
    .box-back{
      height:39%;
    }
  }
  .check-box{
    position: absolute;
    top: 51%;
    left: 1%;
    width: 23%;
    height: 100%;
    .box-back{
      height:47%;
    }
    .func-route{
      box-sizing: border-box;
      .route-heard{
        margin-top: 5px;
        border: 1px solid rgba(3, 45, 96);
        width: 100%;
        display: flex;
        justify-content: space-between;
        height: 22px;
        line-height: 22px;
        font-size: 13px;
        color: white;
        .func-item{
          letter-spacing: 3px;
          width: 50%;
          &:hover{
            cursor: pointer;
          }
        }
      }
      .func{
        height: 42vh;
        width: 100%;
        background-color: rgba(250,250,250);
        .choose-label{
          display: flex;
          align-items: center;
          height: 5vh;
          justify-content: left;
          padding: 0 1vw;
          box-sizing: border-box;
        }
        .label-list{
          width: 98%;
          margin: 0 auto;
          .empty{
            height: 100%;
            width: 100%;
            font-family:'dingding';
            padding: 5vw 0;
            box-sizing:border-box;
          }
        }
        .search{
          .search-btn{
            text-align: left;
            padding-left: 1vw;
            padding-top: 1vh;
            box-sizing: border-box;
          }
          .search-list{
            .empty{
              height: 100%;
              width: 100%;
              font-family:'dingding';
              padding: 5vw 0;
              box-sizing:border-box;
            }
          }
        }
      }
    }
  }

  .uav-live {
    position: absolute;
    top: 9%;
    left: 25.5%;
    width: 42.5%;
    height: 183%;
    .box-back {
      height: 35%;
    }
    .data-title{
      margin:-2% auto 0 auto;
      line-height: 4vh;
    }
  }
  .uav-live-info {
    position: absolute;
    top: 77%;
    left: 25.5%;
    width: 42.5%;
    height: 60%;
    .box-back {
      height: 35%;
    }
    .data-title{
      margin:-2% auto 0 auto;
      line-height: 4vh;
    }
  }
  .uav-charts{
    position: absolute;
    top: 43%;
    left: 69.5%;
    width: 30%;
    height: 157%;
    .box-back {
      height: 35%;
    }
    .data-title{
      margin:-2% auto 0 auto;
      line-height: 4vh;
    }
    .route-heard{
      margin-top: 5px;
      border: 1px solid rgba(3, 45, 96);
      width: 100%;
      display: flex;
      justify-content: space-between;
      height: 22px;
      line-height: 22px;
      font-size: 13px;
      color: white;
      .func-item{
        width: 33%;
        letter-spacing: 3px;
        &:hover{
          cursor: pointer;
        }
      }
    }
    .distance,.task,.person{
      margin-top: 2vh;
      height: 95%;
      width: 100%;
    }
  }
}
.active{
  background:rgba(0, 104, 183);
}

.add-box{
  position: absolute;
  top: 29vh;
  left: 36vw;
  height: 35vh;
  width: 30vw;
  z-index: 999;
  background-color: white;
  color: black;
  border: 2px solid #00BFFF;
  box-sizing: border-box;
  .add-title{
    color: black;
    font-size: 2vh;
    font-family: dingding;
    display: flex;
    justify-content: space-between;
    /* padding: 2vh 1vw; */
    box-sizing: border-box;
    height: 5vh;
    line-height: 5vh;
    border-bottom: 1px solid rgba(245, 245, 245, .7);
    margin-bottom: 1vh;
    padding: 0 1vw;
    .right{
      color: white;
      line-height: 2vh;
      vertical-align: middle;
      padding-top: 1.5vh;
      display: flex;
      justify-content: right;
      .el-button{
        margin-right: 1vw;
      }
      &:hover{
        cursor: pointer;
      }
    }
  }
  .add-body{
    .el-form{
      width: 90%;
      margin: 0 auto;
      :deep(.el-form-item__content){
        justify-content: right;
      }
    }
  }
}

.edit-box{
  position: absolute;
  top: 29vh;
  left: 36vw;
  height: 25vh;
  width: 30vw;
  z-index: 999;
  background-color: white;
  color: black;
  border: 2px solid #00BFFF;
  box-sizing: border-box;
  .edit-title{
    color: black;
    font-size: 2vh;
    font-family: dingding;
    display: flex;
    justify-content: space-between;
    /* padding: 2vh 1vw; */
    box-sizing: border-box;
    height: 5vh;
    line-height: 5vh;
    border-bottom: 1px solid rgba(245, 245, 245, .7);
    margin-bottom: 1vh;
    padding: 0 1vw;
    .right{
      color: white;
      line-height: 2vh;
      vertical-align: middle;
      padding-top: 1.5vh;
      display: flex;
      justify-content: right;
      .el-button{
        margin-right: 1vw;
      }
      &:hover{
        cursor: pointer;
      }
    }
  }
  .edit-body{
    .el-form{
      width: 90%;
      margin: 0 auto;
      :deep(.el-form-item__content){
        justify-content: right;
      }
    }
  }
}
</style>
